package thread;

import java.util.concurrent.atomic.AtomicInteger;

public class ThreadId {
    // Atomic integer containing the next thread ID to be assigned
    private static final AtomicInteger nextId = new AtomicInteger(0);

    // Thread local variable containing each thread's ID
    private static final ThreadLocal<Integer> threadId =
            new ThreadLocal<Integer>() {
                @Override
                protected Integer initialValue() {
                    return nextId.getAndIncrement();
                }
            };

    // Returns the current thread's unique ID, assigning it if necessary
    public static int get() {
        return threadId.get();
    }

    public static void main(String[] args) throws InterruptedException {
        System.out.println(ThreadId.get());

        Thread t = new Thread(() -> {
            System.out.println("thread: " + ThreadId.get());
        });
        t.start();
        t.join();

        Thread t2 = new Thread(() -> {
            System.out.println("thread2: " + ThreadId.get());
        });
        t2.start();
        t2.join();

        System.out.println(ThreadId.get());

    }
}